<template>
  <div class="system-dic-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="500px"
      :close-on-click-modal="false">
      <el-form ref="dicDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col class="mb20">
            <el-form-item label="上级分类" prop="parentId">
              <el-cascader :options="cateData"
                :props="{ checkStrictly: true, value: 'id', label: 'label', emitPath: false }" placeholder="请选择上级分类"
                clearable class="w100" v-model="state.ruleForm.parentId">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col class="mb20">
            <el-form-item label="名称" prop="label">
              <el-input v-model="state.ruleForm.label" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit(dicDialogFormRef)" size="default">{{ state.dialog.submitTxt
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick, reactive, ref } from 'vue';
import { ElMessage } from "element-plus";
import { useQuesApi } from "/@/api/ques";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入api
const quesApi = useQuesApi();
const cateData = ref([])

// 定义变量内容
const dicDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    id: '',
    label: '',
    dicType: '',
    sort: 0,
    parentId: '',
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});

const rules = reactive({
  label: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  parentId: [
    { required: true, message: '请选择上级分类', trigger: 'change' },
  ],
})


// 打开弹窗
const openDialog = (type, dicType, parentId, id) => {

  state.dialog.type = type;
  state.ruleForm.dicType = dicType
  getCateData();

  if (type === 'edit') {
    state.dialog.title = '修改分类';
    state.dialog.submitTxt = '修 改';
    state.ruleForm.id = id;
    quesApi.cateInfo(id).then(res => {
      state.ruleForm = res.data
    })

  } else {
    state.dialog.title = '新增分类';
    state.dialog.submitTxt = '新 增';

    state.ruleForm.parentId = parentId;

    // 清空表单，此项需加表单验证才能使用
    nextTick(() => {
      dicDialogFormRef.value.resetFields();
    });
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

// 获取分类数据
const getCateData = () => {
  if (!state.ruleForm.dicType) {
    ElMessage.error("dicType不能为空")
    return
  }
  quesApi.cateTree().then((res) => {
    cateData.value = [res.data];
  });
};


// 提交
const onSubmit = async (formEl) => {


  if (!formEl) return

  await formEl.validate((valid) => {
    if (valid) {

      if (state.dialog.type === 'add') {
        onAddRow()
      } else {
        onEditRow()
      }
    }
  })



};
// 新增行
const onAddRow = () => {
  quesApi.cateAdd({
    label: state.ruleForm.label,
    dicType: state.ruleForm.dicType,
    parentId: state.ruleForm.parentId,
    sort: state.ruleForm.sort,
  }).then(() => {
    emit('refresh');
    closeDialog();
  })
};

const onEditRow = () => {
  if (state.ruleForm.parentId === state.ruleForm.id) {
    ElMessage.error("上级分类不能是自身")
    return
  }

  quesApi.cateUpdate({
    id: state.ruleForm.id,
    label: state.ruleForm.label,
    dicType: state.ruleForm.dicType,
    parentId: state.ruleForm.parentId,
    sort: state.ruleForm.sort,
  }).then(() => {
    emit('refresh');
    closeDialog();
  })
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
